﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Drawing;
using System.IO;
using System.Net;
using System.Windows.Forms;
using WChat;
using System.Drawing.Imaging;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Globalization;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using NAudio.Wave;

namespace WChat {
    /// <summary>
    /// 微信主要业务逻辑服务类 
    /// </summary>
    public class WXService {
        private Dictionary<string, string> _syncKey = new Dictionary<string, string>();  //同步键值字典
        public static CookieContainer CookiesContainer;
        //同步检查url
        private string _synccheck_url = "https://webpush.wx2.qq.com/cgi-bin/mmwebwx-bin/synccheck?sid={0}&uin={1}&synckey={2}&r={3}&skey={4}&deviceid={5}";
        private string _upload = "https://file.wx2.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json";
        private string login_redirect;
        private BaseService bs = new BaseService();
        private MachingUrl mu = new MachingUrl();

        public object RequestInfo { get; private set; }

        #region 基本
        /// <summary>
        /// 微信初始化
        /// </summary>
        /// <returns></returns>
        public void SetUser(string user) {
            login_redirect = user;
        }
        public JObject WxInit(string login_redirect, int m_url) {
            string init_json = "{{\"BaseRequest\":{{\"Uin\":\"{0}\",\"Sid\":\"{1}\",\"Skey\":\"\",\"DeviceID\":\"e1615250492\"}}}}";
            string uin = CookieDictionary.GetCookies(login_redirect + "Wxuin");
            string sid = CookieDictionary.GetCookies(login_redirect + "Wxsid");

            if (sid != null && uin != null) {
                init_json = string.Format(init_json, uin, sid);
                string cookies = bs.GetCookies(mu.Init_Url(m_url) + "&pass_ticket=" + CookieDictionary.GetCookies(login_redirect + "Ticket"), init_json); //开始设置
                WriteLoginDirect("login", cookies);
                WriteLoginDirect("MyUin", uin);
                CookieDictionary.AddCookies(login_redirect, cookies);
                // MessageBox.Show("微信数据通行证：" + CookieDictionary.GetCookiesByName(login_redirect,8));
                byte[] bytes = bs.MyPostRequest(mu.Init_Url(m_url) + "&pass_ticket=" + CookieDictionary.GetCookies(login_redirect + "Ticket"), init_json, login_redirect);
                if (bytes == null) return null;
                else if (bytes.Count() == 0) return null;
                else {
                    string init_str = Encoding.UTF8.GetString(bytes);
                    JObject init_result = JsonConvert.DeserializeObject(init_str) as JObject;
                    foreach (JObject synckey in init_result["SyncKey"]["List"])  //同步键值
                    {
                        _syncKey.Add(synckey["Key"].ToString(), synckey["Val"].ToString());
                    }
                    return init_result;
                }
            }
            return null;
        }

        public static void WriteLoginDirect(string fileNam, string direct ) {
            string file = path.paths + "\\"+ fileNam + ".txt";   //工作时的路径
            if (File.Exists(file)) {
                File.Delete(file);
            }
            FileStream fs = new FileStream(file, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(direct);
            sw.Close();
        }
        /// <summary>
        /// 获取微信讨论组头像
        /// </summary>
        /// <param name="usename"></param>
        /// <returns></returns>
        public Image GetHeadImg(string usename, string login_redirect, int url) {
            byte[] bytes=null;
            try {
                bytes = bs.GetMyFriendsRequest(mu.GetHead_img(url) + usename, login_redirect);
                if (bytes == null) {
                    return null;
                }
                else if (bytes.Count() == 0) {
                    return null;
                }
                else {
                    return Image.FromStream(new MemoryStream(bytes));
                }
            }
            catch (Exception e) {
                WriteLog.Writelog("GetHeadImg", e.ToString());
            }
            return null;
        }
        /// <summary>
        /// 获取好友头像
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public Image GetIcon(string username, string login_redirect, int url) {
            byte[] bytes = null;
            try {
                bytes = bs.GetMyFriendsRequest(mu.GetIcons(url) + username, login_redirect);
                if (bytes == null) {
                    return null;
                }
                else if (bytes.Count() == 0) {
                    return null;
                }
                else {
                    return Image.FromStream(new MemoryStream(bytes));
                }
            }
            catch (Exception e) {
                WriteLog.Writelog("GetIcon", e.ToString());
            }
            return null;
        }
        /// <summary>
        /// 获取好友列表
        /// </summary>
        /// <returns></returns>
        public JObject GetContact(string login_redirect,int Seq, int _url) {
            byte[] bytes = null;
            string contact_str = "";

            string Skey = CookieDictionary.GetCookies(login_redirect + "SKY");
            long r = (long)(DateTime.Now.ToUniversalTime() - new System.DateTime(1970, 1, 1)).TotalMilliseconds;
            string contact_url = mu.GetContact(_url);
            contact_url = string.Format(contact_url, r, Seq, Skey);

            try {
                bytes = bs.GetMyFriendsRequest(contact_url, login_redirect);
                if (bytes.Count() == 0||bytes== null) {
                    return null;
                }else if(bytes == null) {
                    return null;
                  
                }else {
                    contact_str = Encoding.UTF8.GetString(bytes);
                    return JsonConvert.DeserializeObject(contact_str) as JObject;
                }
            } catch (Exception e) {
                WriteLog.Writelog("GetContact", e.ToString());
            }
            return null;
        }
        /// <summary>
        /// 微信同步检测
        /// </summary>
        /// <returns></returns>

        public JObject WxSyncCheck() {
            string sync_key = "";
            byte[] bytes = null;
            foreach (KeyValuePair<string, string> p in _syncKey) {
                sync_key += p.Key + "_" + p.Value + "%7C";
            }
            sync_key = sync_key.TrimEnd('%', '7', 'C'); 

            string uin = CookieDictionary.GetCookies(login_redirect + "Wxuin");
            string sid = CookieDictionary.GetCookies(login_redirect + "Wxsid");
            if (sid != null && uin != null) {
                _synccheck_url = string.Format(_synccheck_url, sid, uin, sync_key, (long)(DateTime.Now.ToUniversalTime() - new System.DateTime(1970, 1, 1)).TotalMilliseconds, CookieDictionary.GetCookies(login_redirect + "SKY").Replace("@", "%40"), "e1615250492");
               try {
                    bytes = bs.GetMyFriendsRequest(_synccheck_url + "&_=" + DateTime.Now.Ticks, login_redirect);
                    if (bytes != null) {
                        string sync_result = Encoding.UTF8.GetString(bytes);
                        if (sync_result!="") {
                            string[] aArray = sync_result.Split('=');
                           // MessageBox.Show(aArray[1]);
                            return JsonConvert.DeserializeObject(aArray[1]) as JObject;
                        }
                    }
                  }catch (Exception) {
                        throw;
                  }
            }else {
                return null;
            }
            return null;
        }
     
        /// <summary>
        /// 微信同步
        /// </summary>
        /// <returns></returns>
        public JObject WxSync(int url) {
                string sync_json = "{{\"BaseRequest\" : {{\"DeviceID\":\"e1615250492\",\"Sid\":\"{1}\", \"Skey\":\"{5}\", \"Uin\":\"{0}\"}},\"SyncKey\" : {{\"Count\":{2},\"List\":[{3}]}},\"rr\" :{4}}}";
                string uin = CookieDictionary.GetCookies(login_redirect + "Wxuin");
                string sid = CookieDictionary.GetCookies(login_redirect + "Wxsid");
                string sync_keys = "";
                foreach (KeyValuePair<string, string> p in _syncKey) {
                    sync_keys += "{\"Key\":" + p.Key + ",\"Val\":" + p.Value + "},";
                }
                sync_keys = sync_keys.TrimEnd(',');
                sync_json = string.Format(sync_json, uin, sid, _syncKey.Count, sync_keys, (long)(DateTime.Now.ToUniversalTime() - new System.DateTime(1970, 1, 1)).TotalMilliseconds, CookieDictionary.GetCookies(login_redirect + "SKY"));

                if (sid != null && uin != null) {

                    byte[] bytes = bs.MyPostRequest(mu.Sync(url) + sid + "&lang=zh_CN&skey=" + CookieDictionary.GetCookies(login_redirect + "SKY") + "&pass_ticket=" + CookieDictionary.GetCookies(login_redirect + "Ticket"), sync_json, login_redirect);
                    if (bytes != null) {
                        string sync_str = Encoding.UTF8.GetString(bytes);

                        JObject sync_resul = JsonConvert.DeserializeObject(sync_str) as JObject;

                        if (sync_resul["SyncKey"]["Count"].ToString() != "0") {
                            _syncKey.Clear();
                            foreach (JObject key in sync_resul["SyncKey"]["List"]) {
                                _syncKey.Add(key["Key"].ToString(), key["Val"].ToString());
                            }
                        }
                        return sync_resul;
                    }
                    return null;
                }
                else {
                    return null;
                }
            }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="type"></param>
        public void SendMsg(string msg, string from, string to, int type, string login_redirect, int url) {
            string msg_json = "{{" +
            "\"BaseRequest\":{{" +
                "\"DeviceID\" : \"e441551176\"," +
                "\"Sid\" : \"{0}\"," +
                "\"Skey\" : \"{6}\"," +
                "\"Uin\" : \"{1}\"" +
            "}}," +
            "\"Msg\" : {{" +
                "\"ClientMsgId\" : {8}," +
                "\"Content\" : \"{2}\"," +
                "\"FromUserName\" : \"{3}\"," +
                "\"LocalID\" : {9}," +
                "\"ToUserName\" : \"{4}\"," +
                "\"Type\" : {5}" +
            "}}," +
            "\"rr\" : {7}" +
            "}}";
            string uin = CookieDictionary.GetCookies(login_redirect + "Wxuin");
            string sid = CookieDictionary.GetCookies(login_redirect + "Wxsid");
            if (sid != null && uin != null) {
                msg_json = string.Format(msg_json, sid, uin, msg, from, to, type, CookieDictionary.GetCookies(login_redirect + "Ticket"), DateTime.Now.Millisecond, DateTime.Now.Millisecond, DateTime.Now.Millisecond);
                byte[] bytes = bs.MyPostRequest(mu.SendMsg(url) + sid + "&lang=zh_CN&pass_ticket=" + CookieDictionary.GetCookies(login_redirect + "Ticket"), msg_json, login_redirect);
                if (bytes!=null) {
                    string send_result = Encoding.UTF8.GetString(bytes);
                   //  MessageBox.Show(send_result);
                }

            }
        }

        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        /// 
        public Image GetPic(string msgid, string login_redirect, int url) {
            byte[] bytes = null;
            try {
                string picurl = mu.GetPic(url) + msgid + "&skey=" + CookieDictionary.GetCookies(login_redirect + "SKY") + "&type=slave";
                 bytes = bs.GetMyFriendsRequest(picurl, login_redirect);
                if (bytes == null) {
                    return null;
                }
                else if (bytes.Count() == 0) {
                    return null;
                }
                else {
                    return Image.FromStream(new MemoryStream(bytes));
                }
            } catch { }
            return null;
        }
        /// <summary>
        /// 获取真实图片
        /// </summary>
        /// <param name="msgid"></param>
        /// <param name="login_redirect"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public Image GetTruePic(string msgid, string login_redirect, int url) {
            byte[] bytes=null;
            try {              
                string picurl = mu.GetPic(url) + msgid + "&skey=" + CookieDictionary.GetCookies(login_redirect + "SKY");
                bytes = bs.GetMyFriendsRequest(picurl, login_redirect);
                if (bytes == null) {
                    return null;
                }else if(bytes.Count() == 0) {
                    return null;
                }else {
                    return Image.FromStream(new MemoryStream(bytes));
                }       
            } catch { }
            return null;
        }

        /// <summary>
        /// 接受语音消息
        /// </summary>
        /// <param name="msgid"></param>
        /// <param name="login_redirect"></param>
        /// <param name="url"></param>
        public void  GetVoice( string msgid, string login_redirect, int _url ) {
            byte[] bytes = null;
            string voice_url = mu.GetVoiceUrl(_url);
            string Skey = CookieDictionary.GetCookies(login_redirect + "SKY");
            try {
                voice_url = string.Format(voice_url, msgid, Skey); 
                bytes = bs.GetMyFriendsRequest(voice_url, login_redirect);
                if (bytes == null)  return;
                else if (bytes.Count() == 0)  return;
                else {
                    string path = WChat.path.paths + "\\";
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                        FileStream fs = new FileStream(path + msgid+".mp3", FileMode.Create);
                        fs.Write(bytes, 0, bytes.Length);
                        fs.Close();
                }
            }
            catch { }
        }

        //public void getvideo( string msgid, string login_redirect, int url ) {
        //    byte[] bytes = null;
        //    try {
        //        string voice = " https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxgetvideo?msgid=" + msgid + "&skey=" + CookieDictionary.GetCookies(login_redirect + "SKY");
        //        bytes = bs.GetMyFriendsRequest(voice, login_redirect);
        //        if (bytes.Count() == 0) {
        //            MessageBox.Show("空，空，一空空");
        //            return;
        //        }
        //        else {
        //            MessageBox.Show(bytes[0].ToString());
        //            string path = System.Environment.CurrentDirectory + "\\temp\\";
        //            if (!Directory.Exists(path))
        //                Directory.CreateDirectory(path);
        //            FileStream fs = new FileStream(path + msgid + ".avi", FileMode.Create);
        //            fs.Write(bytes, 0, bytes.Length);
        //            fs.Close(); //关闭文件
        //        }
        //    }
        //    catch { }
        //}

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="from_user_name"></param>
        /// <param name="mediaid"></param>
        /// <param name="fromuser"></param>
        /// <param name="login_redirect"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public void GetMedia(string from_user_name, string mediaid, string login_redirect, string filename, int url) {
            string _url = mu.GetFileUrl(url);
            _url = string.Format(_url, from_user_name, mediaid, filename, CookieDictionary.GetCookies(login_redirect + "Wxuin"), CookieDictionary.GetCookies(login_redirect + "Ticket"), CookieDictionary.GetCookiesByName(login_redirect, 8));
            byte[] bytes = bs.GetMyFriendsRequest(_url, login_redirect);
            string path = System.Environment.CurrentDirectory + "\\temp\\";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            try {
                FileStream fs = new FileStream(path + filename, FileMode.Create);
                fs.Write(bytes, 0, bytes.Length);
                fs.Close(); //关闭文件
            }
            catch (Exception) {
                //throw;
            }
          
        }

      
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="type"></param>
        /// <param name="login_redirect"></param>
        /// <param name="url"></param>
        public void Uploadfile(string from, string to, string imageName, string login_redirect) {

            string uin = CookieDictionary.GetCookies(login_redirect + "Wxuin");
            string sid = CookieDictionary.GetCookies(login_redirect + "Wxsid");

            StreamReader sr = new StreamReader("C:/Users/Administrator/Desktop/upload.txt", false);
            string str = sr.ReadLine().ToString();
            sr.Close();
            String boundary = "-----------------------------140683023824016";
            String newLine = "\r\n";

            string upload_json = "{{" + "\"UploadType\" :\"2\","
            + "\"BaseRequest\":{{"
            + "\"Uin\" : \"{0}\","
            + "\"Sid\" : \"{1}\","
            + "\"Skey\" : \"{2}\","
            + "\"DeviceID\" : \"e441551176\","
            + "}},"
              + "\"ClientMediaId\" : \"{3}\","
               + "\"TotalLen\" : \"{4}\","
                + "\"StartPos\" : \"{5}\","
                 + "\"DataLen\" : \"{6}\","
                  + "\"MediaType\" : \"{7}\","
                   + "\"FromUserName\" : \"{8}\","
                    + "\"ToUserName\" : \"{9}\","
                     + "\"FileMd5\" : \"{10}\","
                      + "}}";
            upload_json = string.Format(upload_json, uin, sid, CookieDictionary.GetCookies(login_redirect + "SKY"), DateTime.Now.Millisecond, 20, 0, 20, 4, from, to, "5e6bc3f0ee336c0801b2fcb7a4902290");

            StringBuilder sb = new StringBuilder();
            sb.Append(boundary).Append(newLine);
            sb.Append("Content-Disposition: form-data; name=\"id\"");
            sb.Append(newLine).Append(newLine);
            sb.Append("WU_FILE_6").Append(newLine);

            sb.Append(boundary).Append(newLine);
            sb.Append("Content-Disposition: form-data; name=\"name\"");
            sb.Append(newLine).Append(newLine);
            sb.Append("upload.txt").Append(newLine);

            sb.Append(boundary).Append(newLine);
            sb.Append("Content-Disposition: form-data; name=\"type\"");
            sb.Append(newLine).Append(newLine);
            sb.Append("text/plain").Append(newLine);

            sb.Append(boundary).Append(newLine);
            sb.Append("Content-Disposition: form-data; name=\"lastModifiedDate\"");
            sb.Append(newLine).Append(newLine);
            sb.Append("Thu Mar 09 2017 09:32:08 GMT+0800").Append(newLine);

            sb.Append(boundary).Append(newLine);
            sb.Append("Content-Disposition: form-data; name=\"size\"");
            sb.Append(newLine).Append(newLine);
            sb.Append("20").Append(newLine);

            sb.Append(boundary).Append(newLine);
            sb.Append("Content-Disposition: form-data; name=\"mediatype\"");
            sb.Append(newLine).Append(newLine);
            sb.Append("doc").Append(newLine);

            sb.Append(boundary).Append(newLine);
            sb.Append("Content-Disposition: form-data; name=\"uploadmediarequest\"");
            sb.Append(newLine).Append(newLine);
            sb.Append(upload_json).Append(newLine);
            //sb.Append("{{"\"UploadType\" :\"2\","{{\"BaseRequest\":{\"Uin\":699244040,\"Sid\":\"/p3w2f48GTHbJCFn\",\"Skey\":\"@crypt_c799f4fc_ebd218359c19edb6aabd6890e529fb66\"");
            //sb.Append(",\"DeviceID\":\"e206799846381690\"},\"ClientMediaId\":\"" + DateTime.Now.Millisecond + "\",\"TotalLen\":\"" + 100 + "\",\"StartPos\":0,\"DataLen\"");
            //sb.Append(":\"" + 100 + "\",\"MediaType\":4}\")").Append(newLine);


            sb.Append(boundary).Append(newLine);
            sb.Append("Content-Disposition: form-data; name=\"webwx_data_ticket\"");
            sb.Append(newLine).Append(newLine);
            sb.Append(CookieDictionary.GetCookiesByName(login_redirect, 8)).Append(newLine);
            MessageBox.Show("注意，微信数据通行证：" + CookieDictionary.GetCookiesByName(login_redirect, 8));

            sb.Append(boundary).Append(newLine);
            sb.Append("Content-Disposition: form-data; name=\"pass_ticket\"");
            sb.Append(newLine).Append(newLine);
            sb.Append(CookieDictionary.GetCookies(login_redirect + "Ticket")).Append(newLine);

            sb.Append("Content-Disposition: form-data; name=\"filename\"; filename=\"upload.txt\"").Append(newLine);
            sb.Append("Content-Type:  text/plain");
            sb.Append(newLine).Append(newLine);
            sb.Append(str).Append(newLine);

            sb.Append(boundary).Append(newLine);
            // MessageBox.Show("下面开始广播发消息的数据：");

            if (sid != null && uin != null) {


                byte[] bytes = bs.MyPostRequest(_upload, sb.ToString(), login_redirect);

                string upload_result = Encoding.UTF8.GetString(bytes);
                MessageBox.Show(sb.ToString() + upload_result);
            }
        }

        // int upLoadMediaCount = 0; 
        public bool SendPicMsg(string from, string to, string imageName, string login_redirect, int url) {
            FileStream file = new FileStream(imageName, FileMode.Open);
            file.Seek(0, SeekOrigin.Begin);
            byte[] data = new byte[file.Length];
            int readCount = file.Read(data, 0, data.Length);
            if (readCount != data.Length) return false;
            BaseRequest mBaseReq = new BaseRequest();
            mBaseReq.Uin = CookieDictionary.GetCookies(login_redirect + "Wxuin");
            mBaseReq.Sid = CookieDictionary.GetCookies(login_redirect + "Wxsid");
            mBaseReq.Skey = CookieDictionary.GetCookies(login_redirect + "SKY");
            mBaseReq.DeviceID = "e441551176";
            file.Close();
            string mimetype = "doc";
            var response = Uploadmedia(from, to, "WU_FILE_" + 6, mimetype, 2, 4, data, imageName, CookieDictionary.GetCookies(login_redirect + "Ticket"), mBaseReq, login_redirect, url);
            if (response != null && response.BaseResponse != null && response.BaseResponse.ret == 0) {   //回应不为空，且返回成功
                                                                                                         // upLoadMediaCount++;
                string mediaId = response.MediaId;    //取出MediaId，告知对方发送文件了
                ImgMsg msg = new ImgMsg();
                msg.FromUserName = from;
                msg.ToUserName = to;
                msg.MediaId = mediaId;
                // MessageBox.Show("WXservce-SendPicMsg:的发送文件的媒体id" + mediaId);
                msg.ClientMsgId = DateTime.Now.Millisecond;
                msg.LocalID = DateTime.Now.Millisecond;
                msg.Type = 3;
                var sendImgRep = SendMsgImg(msg, CookieDictionary.GetCookies(login_redirect + "Ticket"), mBaseReq, login_redirect, url);   //第二次发送图片，告知发送成功
                if (sendImgRep != null && sendImgRep.BaseResponse != null && sendImgRep.BaseResponse.ret == 0) {      //回应不为空，且返回成功
                    return true;
                }
                return false;
            }
            else {
                return false;
            }
        }

    
        public bool SendFiles(string from, string to, string imageName, string F_direct, int url) { 
            FileInfo fi = new FileInfo(imageName);
            FileStream file = new FileStream(imageName, FileMode.Open);
            file.Seek(0, SeekOrigin.Begin);
            byte[] data = new byte[file.Length];
            int readCount = file.Read(data, 0, data.Length);
            if (readCount != data.Length) return false;
            BaseRequest mBaseReq = new BaseRequest();
            mBaseReq.Uin = CookieDictionary.GetCookies(F_direct + "Wxuin");
            mBaseReq.Sid = CookieDictionary.GetCookies(F_direct + "Wxsid");
            mBaseReq.Skey = CookieDictionary.GetCookies(F_direct + "SKY");
            mBaseReq.DeviceID = "e441551176";

            string mimetype = "doc";
            var response = Uploadmedia(from, to, "WU_FILE_0", mimetype, 2, 4, data, imageName, CookieDictionary.GetCookies(F_direct + "Ticket"), mBaseReq, F_direct, url);
            if (response != null && response.BaseResponse != null && response.BaseResponse.ret == 0) {   //回应不为空，且返回成功
                                                                                                         //  upLoadMediaCount++;
                string attachid = response.MediaId;    //取出MediaId，告知对方发送文件了
                string content ="<appmsg appid='wx782c26e4c19acffb'sdkver=''><title>文件.txt</title><des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl><appattach><totallen>"+ readCount.ToString() + "</totallen><attachid>"+ attachid +"</attachid ><fileext>txt</fileext></appattach><extinfo></extinfo></appmsg>";
                // MessageBox.Show("from" +from);
                FileMsg msg = new FileMsg();
                msg.FromUserName = from;
                msg.ToUserName = to;
               // MessageBox.Show("content:" + content);
                msg.Content = content;
              //  long r = (long)(DateTime.Now.ToUniversalTime() - new System.DateTime(1970, 1, 1)).TotalMilliseconds;
                //MessageBox.Show("r的值为" + r.ToString());
              //  MessageBox.Show("WXservce-发送文件:的发送文件的媒体id" + attachid);
              //  string tim = DateTime.Now.ToString("yyyyMMddHHmmssfff", DateTimeFormatInfo.InvariantInfo); //生产17位时间戳
              //  Random rad = new Random();//实例化随机数产生器rad；
               // int value = rad.Next(1000, 10000);//用rad生成大于等于1000，小于等于9999的随机数；
               // string suiji = value.ToString(); 
               // string ss = tim.Substring(0, tim.Length - 4);  //左移4位
               // string dd = ss + suiji;  //合并
                msg.ClientMsgId = DateTime.Now.Millisecond;
                msg.LocalID = DateTime.Now.Millisecond;
                msg.Type = 6;
               // string sendImgRep = SendAppMsg(msg, CookieDictionary.GetCookies(F_direct + "Ticket"), mBaseReq, F_direct, url);   //第二次发送post请求，告知对方获取文件
                Wx_SendFileByMediaId(from, F_direct, to, attachid, fi.Name, readCount.ToString(), fi.Extension.Split('.')[1], url);
            }


            return false;
        }

        static long getTimestamp(DateTime time) {
            return (long)(time.ToUniversalTime() - new System.DateTime(1970, 1, 1)).TotalMilliseconds;
        }

        public UploadmediaResponse Uploadmedia(string fromUserName, string toUserName, string id, string mime_type, int uploadType, int mediaType, byte[] buffer, string fileName, string pass_ticket, BaseRequest baseReq, string direct, int url) {
            UploadmediaRequest req = new UploadmediaRequest();
            req.BaseRequest = baseReq;
            req.ClientMediaId = getTimestamp(DateTime.Now);
            req.DataLen = buffer.Length;
            req.StartPos = 0;
            req.TotalLen = buffer.Length;
            req.MediaType = mediaType;
            req.FromUserName = fromUserName;
            req.ToUserName = toUserName;
            req.UploadType = uploadType;
            req.FileMd5 = getMD5(buffer);
            string requestJson = JsonConvert.SerializeObject(req);
            NameValueCollection data = new NameValueCollection();
            data.Add("id", id);
            data.Add("name", fileName);
            data.Add("type", "text/plain");
            data.Add("lastModifiedDate", DateTime.Now.ToString("r") + "+0800 (中国标准时间)");
            data.Add("size", buffer.Length.ToString());
            data.Add("mediatype", mime_type);
            data.Add("uploadmediarequest", requestJson);
            data.Add("webwx_data_ticket", CookieDictionary.GetCookiesByName(direct, 8));
            data.Add("pass_ticket", pass_ticket);
            string repJsonStr = UploadFile_UTF8String(mu.UploadMediaUrl(url), buffer, fileName, mime_type, data, Encoding.UTF8);
            // MessageBox.Show("WXservce-Uploadmedia:的发送文件时返回的json：" + repJsonStr);
            var rep = JsonConvert.DeserializeObject<UploadmediaResponse>(repJsonStr);
            return rep;
        }

        public static string getMD5(byte[] data) {

            MD5 md5Hash = MD5.Create();
            var hash = md5Hash.ComputeHash(data);

            // 创建一个 Stringbuilder 来收集字节并创建字符串  
            StringBuilder sBuilder = new StringBuilder();

            // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串  
            for (int i = 0; i < hash.Length; i++) {
                sBuilder.Append(hash[i].ToString("x2"));
            }

            // 返回十六进制字符串  
            return sBuilder.ToString();

        }

        public SendMsgImgResponse SendMsgImg(ImgMsg msg, string pass_ticket, BaseRequest baseReq, string user, int _url) {
            string url = mu.UploadPicUrl(_url);
            url = string.Format(url, pass_ticket);
            SendMsgImgRequest req = new SendMsgImgRequest();
            req.BaseRequest = baseReq;
            req.Msg = msg;
            req.Scene = 0;
            string requestJson = JsonConvert.SerializeObject(req);
            string repJsonStr = POST_UTF8String(url, requestJson, user);
            var rep = JsonConvert.DeserializeObject<SendMsgImgResponse>(repJsonStr);
            return rep;
        }

        public string SendAppMsg(FileMsg msg, string pass_ticket, BaseRequest baseReq, string user, int _url) {
            string url = mu.UploadFileUrl(_url);
            url = string.Format(url, pass_ticket);
            SendFileRequest req = new SendFileRequest();
            req.BaseRequest = baseReq;
            req.Msg = msg;
            req.Scene = 0;
            string requestJson = JsonConvert.SerializeObject(req);
            string repJsonStr = POST_UTF8String(url, requestJson, user);
            return repJsonStr;
        }

        public string POST_UTF8String(string url, string body, string user) {
            byte[] bytes = bs.MyPostRequest(url, body,user);
            string utf8str = Encoding.UTF8.GetString(bytes);
            return utf8str;
        }

        public byte[] UploadFile(string url, byte[] fileBuf, string fileName, string mime_type, NameValueCollection data, Encoding encoding) {
            string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

            //1.HttpWebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";
            request.Accept = "*/*";
            request.KeepAlive = true;
            request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,ja;q=0.2");
            using (Stream stream = request.GetRequestStream()) {
                //1.1 key/value
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                if (data != null) {
                    foreach (string key in data.Keys) {
                        stream.Write(boundarybytes, 0, boundarybytes.Length);
                        string formitem = string.Format(formdataTemplate, key, data[key]);
                        byte[] formitembytes = encoding.GetBytes(formitem);
                        stream.Write(formitembytes, 0, formitembytes.Length);
                    }
                }

                //1.2 file
                string headerTemplate = "Content-Disposition: form-data; name=\"filename\"; filename=\"{0}\"\r\nContent-Type: " + mime_type + "\r\n\r\n";

                stream.Write(boundarybytes, 0, boundarybytes.Length);
                string header = string.Format(headerTemplate, fileName);
                byte[] headerbytes = encoding.GetBytes(header);
                stream.Write(headerbytes, 0, headerbytes.Length);
                stream.Write(fileBuf, 0, fileBuf.Length);

                //1.3 form end
                stream.Write(endbytes, 0, endbytes.Length);
            }
            //2.WebResponse
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream response_stream = response.GetResponseStream();

            int count = (int)response.ContentLength;
            int offset = 0;
            byte[] buf = new byte[count];
            while (count > 0)  //读取返回数据
            {
                int n = response_stream.Read(buf, offset, count);
                if (n == 0) break;
                count -= n;
                offset += n;
            }
            return buf;
        }

        public string UploadFile_UTF8String(string url, byte[] fileBuf, string fileName, string mime_type, NameValueCollection data, Encoding encoding) {
            var bytes = UploadFile(url, fileBuf, fileName, mime_type, data, encoding);
            string utf8str = Encoding.UTF8.GetString(bytes);
            return utf8str;
        }
      
        public bool VerifyUser(string value,string user_ticket,string direct,int _url) { 
          string verify_url = mu.VeryfyUser(_url); 
            string Uin = CookieDictionary.GetCookies(direct + "Wxuin");
            string Sid = CookieDictionary.GetCookies(direct + "Wxsid");
            string Skey = CookieDictionary.GetCookies(direct + "SKY");
            string pass_ticket= CookieDictionary.GetCookies(direct + "Ticket");
            long r = (long)(DateTime.Now.ToUniversalTime() - new System.DateTime(1970, 1, 1)).TotalMilliseconds;
           // MessageBox.Show("r的值为" + r.ToString());
            verify_url = string.Format(verify_url, r.ToString(), pass_ticket);
            string verify_json = "{" +
                      "\"BaseRequest\":{" +
                                     "\"Uin\":" + Uin+ ","+"\"Sid\":\"" + Sid + "\"," +
                                     "\"Skey\":\"" + Skey +"\"," +
                                     "\"DeviceID\":\"e441551176\""+                             
                                       "}," +
                                           "\"Opcode\":3,"+
                                           "\"VerifyUserListSize\":1,"+
                                           "\"VerifyUserList\":"+"[{" +
                                                                     "\"Value\":\""+ value +"\"," +
                                                                     "\"VerifyUserTicket\":\""+ user_ticket+ "\"}],"+
                                           "\"VerifyContent\":\"\"," +
                                          "\"SceneListCount\":1," +
                                          "\"SceneList\":[33]," +
                                          "\"skey\":\"" + Skey + "\"}";

            //MessageBox.Show("uin为："+Uin + "sid为"+ Sid + "sky为："+Skey + "value为："+ value + "userticket为："+ user_ticket + "还是sky了："+Skey);
           // verify_json = string.Format(verify_json, Uin, Sid, Skey, value, user_ticket, Skey);
            byte[] bytes = bs.MyPostRequest(verify_url, verify_json, direct);
            List<byte[]> lt = new List<byte[]>();
            lt.Add(Encoding.UTF8.GetBytes(verify_json));
            string ret = PostBytes(verify_url, lt, "application/json", null, direct,_url);
            string verify_result = Encoding.UTF8.GetString(bytes); 
           // MessageBox.Show(verify_result);
            return true;
        }
        #endregion
        /*********************************************************************************************************************************************************/
        /// <summary>
        /// 批量获取好友&lang=zh_CN
        /// </summary>
        /// <returns></returns>
        public JObject BatchGetContact( string username, string groupusername, string direct,int _url ) {
            byte[] bytes = null;
            string Uin = CookieDictionary.GetCookies(direct + "Wxuin");
            string Sid = CookieDictionary.GetCookies(direct + "Wxsid");
            string Skey = CookieDictionary.GetCookies(direct + "SKY");
            string pass_ticket = CookieDictionary.GetCookies(direct + "Ticket");

            string url = mu.BatchGetContactUrl(_url);
           
            if (Uin != null && Uin != null) {
                string body = "{{\"BaseRequest\":{{\"Uin\":{0},\"Sid\":\"{1}\",\"Skey\":\"{2}\",\"DeviceID\":\"e441551176\"}},\"Count\":{3},\"List\":{4}}}";
                string content = "[{\"UserName\":\"" + username + "\",\"EncryChatRoomId\":\""+ groupusername+ "\"}]";
                body = string.Format(body, Uin, Sid, Skey, 1, content);
                string bat_url = url + "&r=" + (long)(DateTime.Now.ToUniversalTime() - new System.DateTime(1970, 1, 1)).TotalMilliseconds + "&pass_ticket=" + pass_ticket;
                bytes = bs.MyPostRequest(bat_url, body, direct);
                if (bytes == null) {
                    return null;
                }
                else if (bytes.Count() == 0) {
                    return null;
                }
                else {
                    string contact_str = Encoding.UTF8.GetString(bytes);
                    return JsonConvert.DeserializeObject(contact_str) as JObject;
                }
            }else {
                return null;
            }
        }

        #region 发送文件
        public static string GetFileMd5( string fileName ) {
            try {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++) {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex) {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }

        public void Wx_SendFile( string from, string ToUserName, string filePath, string direct, int _url ) {

            string Uin = CookieDictionary.GetCookies(direct + "Wxuin");
            string Sid = CookieDictionary.GetCookies(direct + "Wxsid");
            string Skey = CookieDictionary.GetCookies(direct + "SKY");
            string pass_ticket = CookieDictionary.GetCookies(direct + "Ticket");
            string deviceid = "e441551176";
            string webwx_data_ticket = CookieDictionary.GetCookiesByName(direct, 8);

            string[] fileTypes = new string[] { "image/jpeg", "image/png", "image/bmp", "image/jpeg", "text/plain", "application/msword", "application/vnd.ms-excel" };
            string[] mediaTypes = new string[] { "pic", "pic", "pic", "doc", "doc", "doc" };
            WeChatUploadFileType FileType = WeChatUploadFileType.Jpeg;

            string ClientMsgId = DateTime.Now.Millisecond.ToString();
            FileInfo file = new FileInfo(filePath);
            if (!file.Exists)
                return;

            string fileMd5 = GetFileMd5(file.FullName);

            byte[] fileData = File.ReadAllBytes(file.FullName);

            #region data
            string data = @"------WebKitFormBoundaryqmAlcppnh4tFP6al
Content-Disposition: form-data; name=""id""

WU_FILE_0
------WebKitFormBoundaryqmAlcppnh4tFP6al
Content-Disposition: form-data; name=""name""

" + file.FullName + @"
------WebKitFormBoundaryqmAlcppnh4tFP6al
Content-Disposition: form-data; name=""type""

" + fileTypes[(int)FileType] + @"
------WebKitFormBoundaryqmAlcppnh4tFP6al
Content-Disposition: form-data; name=""lastModifiedDate""

" + DateTime.Now.ToString("r") + @"+0800 (中国标准时间)
------WebKitFormBoundaryqmAlcppnh4tFP6al
Content-Disposition: form-data; name=""size""

" + fileData.Length.ToString() + @"
------WebKitFormBoundaryqmAlcppnh4tFP6al
Content-Disposition: form-data; name=""mediatype""

" + mediaTypes[(int)FileType] + @"
------WebKitFormBoundaryqmAlcppnh4tFP6al
Content-Disposition: form-data; name=""uploadmediarequest""

{""UploadType"":2,""BaseRequest"":{""Uin"":" + Uin + @",""Sid"":""" + Sid + @""",""Skey"":""" + Skey + @""",""DeviceID"":""" + deviceid + @"""},""ClientMediaId"":" + ClientMsgId + @",""TotalLen"":" + fileData.Length.ToString() + @",""StartPos"":0,""DataLen"":" + fileData.Length.ToString() + @",""MediaType"":4,""FromUserName"":""" + from + @""",""ToUserName"":""" + ToUserName + @""",""FileMd5"":""" + fileMd5 + @"""}
------WebKitFormBoundaryqmAlcppnh4tFP6al
Content-Disposition: form-data; name=""webwx_data_ticket""

" + webwx_data_ticket + @"
------WebKitFormBoundaryqmAlcppnh4tFP6al
Content-Disposition: form-data; name=""pass_ticket""

" + pass_ticket + @"
------WebKitFormBoundaryqmAlcppnh4tFP6al
Content-Disposition: form-data; name=""filename""; filename=""" + file.Name + @"""
Content-Type: " + fileTypes[(int)FileType] + @"";

            #endregion
            byte[] postData = Encoding.UTF8.GetBytes(data);

            byte[] endData = Encoding.UTF8.GetBytes("\r\n------WebKitFormBoundaryqmAlcppnh4tFP6al--\r\n");

            List<byte[]> lt = new List<byte[]>();
            lt.Add(postData);
            lt.Add(fileData);
            lt.Add(endData);

            string url = mu.UploadMediaUrl(_url);
            string ret = PostBytes(url, lt, "*/*", "multipart/form-data; boundary=----WebKitFormBoundaryqmAlcppnh4tFP6al", direct, _url);

            var json = JsonConvert.DeserializeObject<UploadmediaResponse>(ret);

            if (json == null) {
                return;
            }
            string MediaId = json.MediaId;
            Wx_SendFileByMediaId(from, direct, ToUserName, MediaId, file.Name, fileData.Length.ToString(), file.Extension.Split('.')[1], _url);

            //string MsgType = "3";
            //string Content = "";
            //url = "https://" + info.fun + ".qq.com/cgi-bin/mmwebwx-bin/webwxsendmsgimg?fun=async&f=json";
            //data = "{\"BaseRequest\":{\"Uin\":" + info.wxuin + ",\"Sid\":\"" + info.wxsid + "\",\"Skey\":\"" + info.skey + "\",\"DeviceID\":\"" + info.deviceid + "\"},\"Msg\":{\"Type\":" + MsgType + ",\"MediaId\":\"" + MediaId + "\",\"Content\":\"" + Content + "\",\"FromUserName\":\"" + user.UserName + "\",\"ToUserName\":\"" + ToUserName + "\",\"LocalID\":\"" + ClientMsgId + "\",\"ClientMsgId\":\"" + ClientMsgId + "\"},\"Scene\":0}";

            //ret = http.Post(url, data, null, null, "application/json", null);
            //Console.WriteLine(ret);
        }

        public void Wx_SendFileByMediaId( string from, string direct, string ToUserName, string MediaId, string FileName, string FileLength, string FileExtension, int _url ) {

            string Uin = CookieDictionary.GetCookies(direct + "Wxuin");
            string Sid = CookieDictionary.GetCookies(direct + "Wxsid");
            string Skey = CookieDictionary.GetCookies(direct + "SKY");
            string pass_ticket = CookieDictionary.GetCookies(direct + "Ticket");
            string deviceid = "e441551176";
            string webwx_data_ticket = CookieDictionary.GetCookiesByName(direct, 8);

            string MsgType = "6";
            string Content = "<appmsg appid='wxeb7ec651dd0aefa9' sdkver=''><title>" + FileName + "</title><des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl><appattach><totallen>" + FileLength + "</totallen><attachid>" + MediaId + "</attachid><fileext>" + FileExtension + "</fileext></appattach><extinfo></extinfo></appmsg>";
            string ClientMsgId = DateTime.Now.Millisecond.ToString();
            string fil_url = mu.UploadFileUrl(_url);
            string pic_url = mu.UploadPicUrl(_url);
            string data = "{\"BaseRequest\":{\"Uin\":" + Uin + ",\"Sid\":\"" + Sid + "\",\"Skey\":\"" + Skey + "\",\"DeviceID\":\"" + deviceid + "\"},\"Msg\":{\"Type\":" + MsgType + ",\"Content\":\"" + Content + "\",\"FromUserName\":\"" + from + "\",\"ToUserName\":\"" + ToUserName + "\",\"LocalID\":\"" + ClientMsgId + "\",\"ClientMsgId\":\"" + ClientMsgId + "\"},\"Scene\":0}";

            //string ret = http.Post(url, data, null, null, "application/json", null);
            List<byte[]> lt = new List<byte[]>();
            lt.Add(Encoding.UTF8.GetBytes(data));

            //switch (FileExtension.ToLower()) {
            //case ".jpg":
            //PostBytes(pic_url, lt, "application/json", null, direct, _url);
            //break;
            //case ".png":
            //PostBytes(pic_url, lt, "application/json", null, direct, _url);
            //break;
            //case ".bmp":
            //PostBytes(pic_url, lt, "application/json", null, direct, _url);
            //break;
            //case ".txt":
            //PostBytes(fil_url, lt, "application/json", null, direct, _url);
            // break;
            //case ".doc":
            //PostBytes(fil_url, lt, "application/json", null, direct, _url);
            // break;
            //case ".xls":
            //PostBytes(fil_url, lt, "application/json", null, direct, _url);
            //break;
            //}
            string ret = PostBytes(fil_url, lt, "application/json", null, direct, _url);
        }

        public string PostBytes( string url, List<byte[]> postDatas, string accept, string contenttype, string direct, int _url ) {
            string referer = mu.WUrl(_url);
            ServicePointManager.Expect100Continue = false;

            HttpWebRequest httpWebRequest = null;

            HttpWebResponse httpWebResponse = null;
            try {
                if (url.ToLower().StartsWith("https", StringComparison.OrdinalIgnoreCase)) {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                    httpWebRequest.ProtocolVersion = HttpVersion.Version10;
                }
                else
                    httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);

                // httpWebRequest.CookieContainer = RequestInfo.Cookie;
                // httpWebRequest.CookieContainer = CookieDictionary.GetCookies(direct);
                httpWebRequest.Headers.Add("Cookie", CookieDictionary.GetCookies(direct));
                if (referer != null && referer.Length > 0)
                    httpWebRequest.Referer = referer;

                if (contenttype != null && contenttype.Length > 0)
                    httpWebRequest.ContentType = contenttype;

                if (accept != null && accept.Length > 0)
                    httpWebRequest.Accept = accept;

                httpWebRequest.AllowAutoRedirect = false;


                httpWebRequest.ServicePoint.ConnectionLimit = 10;

                httpWebRequest.Method = postDatas != null ? "POST" : "GET";
                // httpWebRequest.Timeout = 10000;

                if (postDatas != null) {
                    int totalLength = 0;

                    foreach (byte[] b in postDatas) {
                        totalLength += b.Length;
                    }
                    httpWebRequest.ContentLength = totalLength;
                    Stream stream = httpWebRequest.GetRequestStream();

                    foreach (byte[] b in postDatas) {
                        stream.Write(b, 0, b.Length);
                    }

                    stream.Close();
                }

                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                string html = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();

                //currentTry = 0;

                WebHeaderCollection webHeader = new WebHeaderCollection();
                webHeader = httpWebResponse.Headers;
                httpWebRequest.Abort();
                httpWebResponse.Close();

                // foreach (Cookie cookie in httpWebResponse.Cookies) {
                //   RequestInfo.Cookie.Add(cookie);
                //  }

                return html;
            }
            catch (Exception e) {
                if (httpWebRequest != null) {
                    httpWebRequest.Abort();
                }
                if (httpWebResponse != null) {
                    httpWebResponse.Close();
                }
                Console.WriteLine("ClsHttp.Get:" + e.Message);
                return "";
            }
        }

        public static bool CheckValidationResult( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors ) {
            return true; //总是接受  
        }

        public enum WeChatUploadFileType { Jpeg, Png, Bmp, Txt, Word, Xls }

        #endregion

        #region 群操作和加好友

        /// <summary>
        /// 添加好友
        /// </summary>
        /// <param name="direct"></param>
        /// <param name="speak"></param>
        /// <param name="userNam"></param>
        /// <returns></returns>
        public JObject AddFriend( string direct, string speak, string userNam, int _url ) {
            byte[] bytes = null;
            string url = mu.AddFrieUrl(_url);
            long r = (long)(DateTime.Now.ToUniversalTime() - new System.DateTime(1970, 1, 1)).TotalMilliseconds;
            string pass_ticket = CookieDictionary.GetCookies(direct + "Ticket");
            string uin = CookieDictionary.GetCookies(direct + "Wxuin");
            string sid = CookieDictionary.GetCookies(direct + "Wxsid");
            string Skey = CookieDictionary.GetCookies(direct + "SKY");
            url = string.Format(url, r, pass_ticket);

            string body = "{{" +
                  "\"BaseRequest\":{{" +
                                       "\"Uin\":\"{0}\"," +
                                       "\"Sid\":\"{1}\"," +
                                       "\"Skey\":\"{2}\"," +
                                       "\"DeviceID\":\"e441551176\"" +
                                    "}}," +
                  "\"Opcode\":2 ," +
                  "\"VerifyUserListSize\":1 ," +
                  "\"VerifyUserList\":[{{" +
                                         "\"Value\":\"{3}\"," +
                                         "\"VerifyUserTicket\":\"\"" +
                                      "}}] ," +
                  "\"VerifyContent\":\"{4}\"," +
                  "\"SceneListCount\":1," +
                  "\"SceneList\":[33]," +
                    "\"skey\":\"{5}\"" +
                     "}}";
            body = string.Format(body, uin, sid, Skey, userNam, speak, Skey);
            bytes = bs.MyPostRequest(url, body, direct);
            if (bytes == null) return null;
            else if (bytes.Count() == 0) return null;
            else {
                WriteLog.Writelog("AddFriend", Encoding.UTF8.GetString(bytes));
               // MessageBox.Show(Encoding.UTF8.GetString(bytes));
                return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(bytes)) as JObject;
            }
           // return null;
        }
        /// <summary>
        /// 更新群聊
        /// </summary>
        /// <param name="direct"></param>
        /// <param name="username"></param>
        /// <param name="chatroom_nam"></param>
        /// <returns></returns>
        public JObject UpdataChatRoom( string direct, string username, string chatroom_nam, int _url ) {
            string pass_ticket = CookieDictionary.GetCookies(direct + "Ticket");
            string addurl = mu.UpdChRoUrl(_url) + pass_ticket;
            string uin = CookieDictionary.GetCookies(direct + "Wxuin");
            string sid = CookieDictionary.GetCookies(direct + "Wxsid");
            string Skey = CookieDictionary.GetCookies(direct + "SKY");
            string body = "{{" +
                                "\"AddMemberList\":\"{0}\"," +
                                "\"ChatRoomName\":\"{1}\"," +
                                "\"BaseRequest\":{{" +
                                                   "\"Uin\":\"{2}\"," +
                                                   "\"Sid\":\"{3}\"," +
                                                   "\"Skey\":\"{4}\"," +
                                                   "\"DeviceID\":\"e441551176\"" +
                                                 "}}" +
                          "}}";
            body = string.Format(body, username, chatroom_nam, uin, sid, Skey);
            byte[] bytes = bs.MyPostRequest(addurl, body, direct);
          
            if (bytes == null) return null;
            else if (bytes.Count() == 0) return null;
            else {
                string result = Encoding.UTF8.GetString(bytes);
                return JsonConvert.DeserializeObject(result) as JObject;
            }
        }
        /// <summary>
        /// 创建群聊
        /// </summary>
        /// <param name="direct"></param>
        /// <param name="count"></param>
        /// <param name="user_name"></param>
        /// <returns></returns>
        public JObject CreateChatRoom( string direct, int count, List<string> user_name, int _url, string Topic ) {
            byte[] bytes = null;
            string pass_ticket = CookieDictionary.GetCookies(direct + "Ticket");
            long r = (long)(DateTime.Now.ToUniversalTime() - new System.DateTime(1970, 1, 1)).TotalMilliseconds;
            string url = mu.CreChaRoUrl(_url);
            url = string.Format(url, r, pass_ticket);
            string UserList = string.Empty;
            if (user_name != null) {
                foreach (var us_na in user_name) {
                    UserList += "{" + "\"UserName\":\"" + us_na + "\"},";
                }
                UserList = UserList.TrimEnd(',');
            }
            string uin = CookieDictionary.GetCookies(direct + "Wxuin");
            string sid = CookieDictionary.GetCookies(direct + "Wxsid");
            string skey = CookieDictionary.GetCookies(direct + "SKY");
            string body = "{{" +
                "\"MemberCount\":{0}," +
                "\"MemberList\":[{1}]," +
                "\"Topic\":\"{2}\"," +
                "\"BaseRequest\":{{" +
                                       "\"Uin\":\"{3}\"," +
                                       "\"Sid\":\"{4}\"," +
                                       "\"Skey\":\"{5}\"," +
                                       "\"DeviceID\":\"e441551176\"" +
                                    "}}" +
                           "}}";
            body = string.Format(body, count, UserList, Topic, uin, sid, skey);
            bytes = bs.MyPostRequest(url, body, direct);
            if (bytes != null) {
                WriteLog.Writelog("CreateChatRoom", Encoding.UTF8.GetString(bytes));
               // MessageBox.Show(Encoding.UTF8.GetString(bytes));
                return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(bytes)) as JObject;
            }
            return null;
        }

        #endregion

        public JObject ClickLogin(string file,string uin) {
            byte[] bytes = null;
            string login_url = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxpushloginurl?uin={0}";

             login_url = string.Format(login_url, uin);
              if (uin!=string.Empty) {
                bytes = bs.GetRequestFromFile(login_url, file);
                if (bytes == null) {
                    return null;
                }
                else if (bytes.Count() == 0) {
                    return null;
                }
                else {
                    string clogin = Encoding.UTF8.GetString(bytes);
                    return JsonConvert.DeserializeObject(clogin) as JObject;
                }
            }
            return null;
        }

        public void Test(string url) {
            byte[] bytes = null;
            bytes = bs.SendGetRequest(url);
            string result = Encoding.UTF8.GetString(bytes);
            MessageBox.Show(result);
        }
    }
}
